package com.moshang.blog.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.entity.vo.TableField;
import com.moshang.blog.entity.vo.TableVO;
import com.moshang.blog.mapper.TableMapper;
import com.moshang.blog.service.TableService;
import com.moshang.blog.core.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @program: blog
 * @description: ${description}
 * @author: xieweiwei
 * @create: 2018-10-11 10:22
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class TableServiceImpl implements TableService {
   @Resource
   private TableMapper tableMapper;

    @Override
    public Page<TableVO> selectTablePage(Page<TableVO> objectPage, String searchKey, String searchValue) {
        List<TableVO> list = tableMapper.listPage(searchKey,searchValue,objectPage);
        objectPage.setRecords(list);
        return objectPage;
    }

    @Override
    public Integer getTableCount() {
        return tableMapper.getTableCount();
    }

    @Override
    public List<TableVO> findAllTables(Map<String, Object> params) {
        List<TableVO> list = tableMapper.findList(params);
        return list;

}


    @Override
    public TableVO detailTable(String name) {
        return tableMapper.selectDetailTable(name);
    }
    @Override
    public List<TableField> selectFields(Map<String,Object> map) {
        return tableMapper.selectFields(map);
    }

    @Override
    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for(String tableName : tableNames){
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }


    public Map<String, String> queryTable(String tableName) {
        return tableMapper.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return tableMapper.queryColumns(tableName);
    }
}
